// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using KnessetCore.Members.Views;
using KnessetCore.Utils;
using log4net;
using KnessetCore.Members;

namespace KnessetCore.Updaters
{
	/// <summary>
	/// Updates new knesset members that joined the Knesset.
	/// </summary>
	public class NewMembersUpdater : IUpdater<ICollection<MemberView>>
	{
		#region Private variables
		private readonly ILog logger = LogManager.GetLogger("KnessetCore.Updaters");
		#endregion

		#region IUpdater<ICollection<string>> Members

		/// <summary>
		/// Update a persistent object (like db or file) with the appropriate values.
		/// </summary>
		/// <param name="updateData">Update with this values. Can not be null.</param>
		/// <exception cref="UpdateException">Error while updating.</exception>
		public void Update(ICollection<MemberView> updateData)
		{
			logger.Debug("Entered NewMembersUpdater.Update");
			if (updateData == null) throw new ArgumentNullException("updateData");
			foreach (MemberView knessetMember in updateData)
			{
				// Check if member exists.
				if (!KnessetMembers.GetInstance().IsExist(knessetMember.Name))
				{
					logger.Info(string.Format("Member {0} does not exists adding to ParliamentMembers table.", knessetMember));
					// Add to members.
					try
					{

						KnessetMembers.GetInstance().Add(knessetMember);
					}
					catch (KnessetMembersException e)
					{
						logger.Error(string.Format("Error while trying to update: {0}", e.Message));
						// Continue to the next member.
					}
				}
			}

			// Do a sanity check. Sometimes names are being changed (letters are removed added and therefore a new
			// name is added).
			if (KnessetMembers.GetInstance().GetMembers().Count > 120)
			{
				Constants.TextChangedLogger.Error("Number of Knesset members had exceeded 120.");
			}
			logger.Debug("Exited NewMembersUpdater.Update");
		}

		#endregion
	}
}